package com.design.classroommanagement.activity

import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.design.classroommanagement.R
import com.design.classroommanagement.api.ApiManager
import com.design.classroommanagement.api.Role
import com.design.classroommanagement.databinding.ActivityRegisterBinding
import com.laughing.lib.base.HBaseActivity
import com.laughing.lib.base.HBaseViewModel
import com.laughing.lib.base.getVm
import com.laughing.lib.utils.Logs
import com.laughing.lib.utils.runInBg
import com.laughing.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.activity_register.et_account
import kotlinx.android.synthetic.main.activity_register.et_pwd

class RegisterActivity : HBaseActivity<HBaseViewModel, ActivityRegisterBinding>() {

    private var role: Role = Role.admin

    override fun initCompleted() {
        binding.apply {
            rgroup.setOnCheckedChangeListener { radiogroup, i -> onSelectTab() }
            onSelectTab()
            btn_register.setOnClickListener(View.OnClickListener {
                runInBg {
                    val account = et_account.text.toString().trim { it <= ' ' }
                    val pwd = et_pwd.text.toString().trim { it <= ' ' }
                    val pwdTwo = et_pwd_sure.text.toString().trim { it <= ' ' }
                    Logs.d("account $account")
                    Logs.d("pwd $pwd")
                    Logs.d("pwdTwo $pwdTwo")
                    if (TextUtils.isEmpty(account)) {
                        showToast("请输入用户名")
                    } else if (TextUtils.isEmpty(pwd)) {
                        showToast("请输入密码")
                    } else if (TextUtils.isEmpty(pwdTwo)) {
                        showToast("请再次输入密码")
                    } else if (pwd != pwdTwo) {
                        showToast("输入两次的密码不一样")
                    } else if (ApiManager.getUser(account, role) != null) {
                        showToast("此账户名已经存在")
                    } else {
                        ApiManager.register(account, pwd, role)
                        //                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                        val intent = Intent(this@RegisterActivity, LoginActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
            })
        }

    }

    private fun onSelectTab() {
        when (binding.rgroup.checkedRadioButtonId) {
            R.id.admin -> {
                role = Role.admin
            }
            R.id.teacher -> {
                role = Role.teacher
            }
            R.id.student -> {
                role = Role.student
            }
        }
    }


}